<template>
  <!-- 包赔信息-->
  <el-dialog :title="title" :visible="dialogVisible" :close-on-click-modal="false" width="1000px" @close="close">
    <div class="form-box" v-loading="loading">
      <el-descriptions v-if="orderInfo" class="margin-top" title="" :column="3" border>

        <el-descriptions-item label="卖家">
          {{orderInfo.sellerName}}<span v-if="orderInfo.orderType==2">({{ orderInfo.sellerTenantName }})</span>
        </el-descriptions-item>
        <el-descriptions-item label="买家">
          {{orderInfo.buyerTenantName}}
        </el-descriptions-item>
        <el-descriptions-item label="商品金额">
          {{orderInfo.backAmount}}
        </el-descriptions-item>
        <el-descriptions-item label="包赔商">
          {{orderInfo.guaranteeTenantName}}
        </el-descriptions-item>
        <el-descriptions-item label="包赔客服">
          {{orderInfo.guaranteeName}}
        </el-descriptions-item>
        <el-descriptions-item label="包赔合同">
          <span v-if="orderInfo.signContractState==1">未发起合同</span>
          <span v-if="orderInfo.signContractState==2" class="link">签署中</span>
          <span v-if="orderInfo.signContractState==3" class="link">已签署</span>
        </el-descriptions-item>
        <el-descriptions-item label="卖家IP" :span="3">
          {{form.ip}} {{form.ipAddr}}
        </el-descriptions-item>
        <el-descriptions-item  :span="3" label="卖家定位" v-if="orderInfo.gpsAddr">
          {{orderInfo.gpsAddr}}
        </el-descriptions-item>
      </el-descriptions>
      <div style="height:15px"></div>
      <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="100px" class="demo-ruleForm">

        <el-form-item label="姓名" prop="name">
          <el-input :disabled="!isEdit" v-model="form.name" placeholder="请输入卖家姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <div class="flex">
            <el-input :disabled="!isEdit" v-model="form.idCard" placeholder="请输入卖家身份证号" />
            <span style="width: 100px;margin-left: 10px;">年龄:<span :style="{color:`${getUserAge>=18?'#333':'red'}`}">{{getUserAge}}</span></span>
          </div>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input :disabled="!isEdit" v-model="form.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="地址" prop="adress">
          <el-input :disabled="!isEdit" v-model="form.adress" placeholder="请输入卖家地址" />
        </el-form-item>
        <el-form-item label="家庭人员资料" prop="familyRemark">
          <el-input :disabled="!isEdit" style="width:600px" type="textarea" rows="6" v-model="form.familyRemark" placeholder="请输入家庭人员资料" />
        </el-form-item>
        <div class="checkSmTool" v-loading="checkLoading">
          <div style="font-size:16px;font-weight:bold;margin-bottom:10px;padding-left:20px">实名检测工具：
            <span style="margin-left:15px">
              <el-tag v-if="checkRes&&checkRes.bankStatus=='01'" type="success">一致</el-tag>
              <el-tag v-if="checkRes&&checkRes.bankStatus=='02'" type="danger">不一致</el-tag>
            </span>
          </div>
          <el-form :model="checkForm" :rules="checkFormRules" ref="checkForm" :inline="true" label-width="70px">
            <el-form-item label="姓名" prop="inputName">
              <el-input style="width:200px" v-model="checkForm.inputName" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="手机号" prop="inputMobile">
              <el-input style="width:200px" v-model="checkForm.inputMobile" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item class="btns">
              <el-button type="primary" icon="el-icon-search" @click="check" class="zdy-btn">查询</el-button>
              <el-button type="warning" icon="el-icon-set-up" @click="checkHis" class="zdy-btn">历史记录</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-form-item label="其他信息" prop="otherRemark">
          <el-input :disabled="!isEdit" style="width:600px" type="textarea" rows="6" v-model="form.otherRemark" placeholder="请输入实名备注" />
        </el-form-item>
        <!-- <el-form-item label="补充信息" prop="remark">
          <el-input :disabled="!isEdit" style="width:600px" type="textarea" rows="6" v-model="form.remark" placeholder="请输入补充信息" />
        </el-form-item> -->
        <el-form-item label="身份证国徽面" prop="emblemIdcardImg" :class="{ 'hiddenupload': form.emblemIdcardImg }">
          <div class="flex">
            <el-input v-model="form.emblemIdcardImg" v-show="false"></el-input>
            <el-upload :disabled="!isEdit" class :action="uploadImgUrl" :file-list="idcardImg1" :show-file-list="true" list-type="picture-card" :limit="1" :on-success="handleAvatarSuccess1" :on-remove="handleAvatarRemove1" :on-preview="handlePictureCardPreview">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="身份证人像面" prop="faceIdcardImg" :class="{ 'hiddenupload': form.faceIdcardImg }">
          <div class="flex">
            <el-input v-model="form.faceIdcardImg" v-show="false"></el-input>
            <el-upload :disabled="!isEdit" class :action="uploadImgUrl" :file-list="idcardImg2" :show-file-list="true" list-type="picture-card" :limit="1" :on-success="handleAvatarSuccess2" :on-remove="handleAvatarRemove2" :on-preview="handlePictureCardPreview">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="手持身份证" prop="handIdcardImg" :class="{ 'hiddenupload': form.handIdcardImg }">
          <div class="flex">
            <el-input v-model="form.handIdcardImg" v-show="false"></el-input>
            <el-upload :disabled="!isEdit" class :action="uploadImgUrl" :file-list="idcardImg3" :show-file-list="true" list-type="picture-card" :limit="1" :on-success="handleAvatarSuccess3" :on-remove="handleAvatarRemove3" :on-preview="handlePictureCardPreview">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item>
        <el-row>
          <el-form-item label="其他图片" prop>
            <el-upload :disabled="!isEdit" :action="uploadImgUrl" :file-list="imgShowList" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-exceed="uploadNumber" :multiple="true" :drag="true" :on-success="handleUploadSuccess" :limit="10" :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-row>
        <div class="center">
          <el-button type="warning" plain @click="isEdit=true" v-show="!isEdit&&dialogType=='edit'">编辑</el-button>
          <el-button type="primary" @click="save" v-show="isEdit">保存</el-button>
          <!-- <el-button type="primary" @click="submitForm('form')"  v-loading="loading">审核通过</el-button> -->
        </div>
      </el-form>

      <el-dialog title="实名检测记录" append-to-body :visible.sync="historyVisible" width="1000px">
        <div>
          <smCheckDialog></smCheckDialog>

        </div>
      </el-dialog>
    </div>
  </el-dialog>
</template>

<script>
import onSelfApi from "@/api/retrieveManage/onSelf.js";
import shimingApi from "@/api/utilsPages/shimingTest.js";
import smCheckDialog from "@/views/tenantPages/tools/shimingTest/index.vue";
import baopeiApi from "@/api/retrieveManage/baopei.js";
export default {
  name: "baopeiInfo",
  components: { smCheckDialog },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      dialogType: "edit",
      title: "",
      isEdit: false,
      uploadImgUrl: "",
      imgShowList: [],
      newImages: [],
      imgFileList: [],

      idcardImg1: [],
      idcardImg2: [],
      idcardImg3: [],
      // 表单参数
      form: {
        name: "",
        phoneNumber: "",
        idCard: "",
        adress: "",
        otherRemark: "",
        faceIdcardImg: "",
        emblemIdcardImg: "",
        handIdcardImg: "",
        img: "",
      },

      checkForm: {
        inputMobile: "",
        inputName: "",
      },
      checkRes: "",
      checkLoading: false,
      historyVisible: false,

      orderInfo: null,
      rules: {
        // nickName: [
        //   { required: true, message: "请输入号商名称", trigger: "blur" }
        // ]
      },
      checkFormRules: {
        inputMobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
        ],
        inputName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      },
    };
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
  },
  computed: {
    getUserAge() {
      if (this.form.idCard && this.form.idCard.length == 18) {
        return this.getAge(this.form.idCard);
      } else {
        return "暂无";
      }
    },
  },
  methods: {
    // 打开弹窗
    async open(data, flag) {
      this.dialogType = flag;
      this.checkRes = "";
      this.checkForm = {
        inputMobile: "",
        inputName: "",
      };
      this.newImages = [];
      this.imgShowList = [];
      this.imgFileList = [];
      this.idcardImg1 = [];
      this.idcardImg2 = [];
      this.idcardImg3 = [];
      this.title = "包赔信息";
      this.isEdit = false;
      this.orderInfo = data;
      console.log("%c Line:217 🥒 this.orderInfo", "color:#465975", this.orderInfo);
      // this.form.id = this.orderInfo.id
      // this.getGuaranteeInfo()
      this.dialogVisible = true;
      if (this.orderInfo.guaranteeInfo) {
        this.form = JSON.parse(this.orderInfo.guaranteeInfo);
        this.showImgList();
      } else {
        // 查询包赔资料
        const info = await this.getByTypeAndBusinessId(this.orderInfo.sellerId);
        if (info) {
          this.$alert(
            "该订单没有包赔资料，将为你自动填充用户包赔认证信息，请自行保存！",
            "提示",
            {
              confirmButtonText: "确定",
              callback: (action) => {
                this.form = { ...info };
                this.showImgList();
                this.isEdit = true;
              },
            }
          );
        } else {
          this.$alert(
            "该用户没有进行包赔认证，请提醒用户进行包赔认证！",
            "提示",
            {
              confirmButtonText: "确定",
              callback: (action) => {},
            }
          );
        }
      }
    },
    // 查询包赔认证信息
    async getByTypeAndBusinessId(userId) {
      try {
        const res = await baopeiApi.getByTypeAndBusinessId({
          type: 1,
          businessId: userId,
        });
        if (res.data) {
          return res.data;
        } else {
          return false;
        }
      } catch (error) {
        return false;
      }
    },
    // 查询实名
    check() {
      this.$refs["checkForm"].validate((valid) => {
        if (valid) {
          this.checkLoading = true;
          shimingApi
            .check(this.checkForm)
            .then((res) => {
              this.checkLoading = false;
              this.checkRes = res.data || "";
              this.$refs.shengyu.getNumber();
            })
            .catch((err) => {
              this.checkLoading = false;
            });
        } else {
          this.$alert("请填写姓名和手机号！");
        }
      });
    },
    // 打开手机号实名查询记录弹窗
    checkHis() {
      this.historyVisible = true;
    },
    // 查看合同
    viewContract() {
      onSelfApi
        .getDownLoadUrlById({
          id: this.orderInfo.signContractId,
        })
        .then((res) => {
          if (res.code == 200) {
            window.open(res.msg);
          }
        });
    },

    // 回显图片
    showImgList() {
      this.imgShowList = [];
      this.imgFileList = [];
      if (this.form.emblemIdcardImg) {
        this.idcardImg1 = [
          {
            url: this.form.emblemIdcardImg,
            name: "",
          },
        ];
      }
      if (this.form.faceIdcardImg) {
        this.idcardImg2 = [
          {
            url: this.form.faceIdcardImg,
            name: "",
          },
        ];
      }
      if (this.form.handIdcardImg) {
        this.idcardImg3 = [
          {
            url: this.form.handIdcardImg,
            name: "",
          },
        ];
      }
      if (this.form.img) {
        let arr = JSON.parse(this.form.img);
        this.imgShowList = JSON.parse(JSON.stringify(arr));
        this.imgFileList = JSON.parse(JSON.stringify(arr));
      }
    },

    // 重置
    reset() {
      // this.form = {
      //     backOrderId: '',
      //     name: '',
      //     phoneNumber: '',
      //     idCard: '',
      //     adress: '',
      //     remark: '',
      //     faceIdcardImg: '',
      //     emblemIdcardImg: '',
      //     img: '',
      //     ip: ''
      // }
      this.$refs.form.resetFields();
    },
    // 图片数组预览
    imgView(list, and) {
      this.$viewerApi({
        images: list,
        options: {
          initialViewIndex: and,
        },
      });
    },

    // 保存资料
    async save() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          // 拼接新上传的图片
          let oldArr = [];
          if (this.imgFileList && this.imgFileList.length) {
            this.imgFileList.forEach((img) => {
              oldArr.push({
                url: img.url,
              });
            });
          }
          if (this.newImages && this.newImages.length) {
            // let newArr = []

            this.newImages.forEach((img) => {
              oldArr.push({
                url: img.response.data.filePath,
              });
            });

            // this.form.img = JSON.stringify(
            //     this.imgFileList.concat(this.newImages)
            // )
          } else {
          }
          this.form.img = JSON.stringify(oldArr);

          // 保存
          const obj = {
            id: this.orderInfo.id,
            guaranteeInfo: JSON.stringify(this.form),
          };
          let res = await onSelfApi.backClueOrderupdateSome(obj);
          this.dialogVisible = false;
          this.$parent.getList();
          this.$message.success(res.msg);
          this.isEdit = false;
        } else {
          this.$alert("请填写完整！");
        }
      });
    },
    async submitForm(formName) {
      // auditGuaranteeInfo

      this.$confirm("审核通过后不可撤销，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await this.save();
          onSelfApi
            .auditGuaranteeInfo({ id: this.form.backOrderId })
            .then((res) => {
              this.$alert(res.msg);
              this.close();
            });
        })
        .catch(() => {});
    },
    // 身份证图片相关---start----
    // 身份证国徽面移除
    handleAvatarRemove1(response, file) {
      this.form.emblemIdcardImg = "";
      this.idcardImg1 = [];
    },
    // 身份证国徽面上传成功
    handleAvatarSuccess1(res, file) {
      if (res.code == 200) {
        this.form.emblemIdcardImg = res.data.filePath;
      }
    },
    // 身份证人像面面图片移除
    handleAvatarRemove2(response, file) {
      this.form.faceIdcardImg = "";
      this.idcardImg2 = [];
    },
    // 身份证人像面片上传成功
    handleAvatarSuccess2(res, file) {
      if (res.code == 200) {
        this.form.faceIdcardImg = res.data.filePath;
      }
    },
    // 手持身份证图片移除
    handleAvatarRemove3(response, file) {
      this.form.idCardSC = "";
      this.idcardImg3 = [];
    },
    // 手持身份证图片上传成功
    handleAvatarSuccess3(res, file) {
      if (res.code == 200) {
        this.form.handIdcardImg = res.data.filePath;
      }
    },

    // // 父亲身份证正面图片移除
    // handleAvatarRemove4(response, file) {
    //     this.form.fidCardZ = ''
    //     this.idcardImg4 = []
    // },
    // // 父亲身份证面上传成功
    // handleAvatarSuccess4(res, file) {
    //     if (res.code == 200) {
    //         this.form.fidCardZ = res.data.filePath
    //     }
    // },

    // // 父亲身份证反面图片移除
    // handleAvatarRemove5(response, file) {
    //     this.form.fidCardF = ''
    //     this.idcardImg5 = []
    // },
    // // 父亲身份证反面上传成功
    // handleAvatarSuccess5(res, file) {
    //     if (res.code == 200) {
    //         this.form.fidCardF = res.data.filePath
    //     }
    // },

    // // 母亲身份证正面图片移除
    // handleAvatarRemove6(response, file) {
    //     this.form.midCardZ = ''
    //     this.idcardImg6 = []
    // },
    // // 母亲身份证正面上传成功
    // handleAvatarSuccess6(res, file) {
    //     if (res.code == 200) {
    //         this.form.midCardZ = res.data.filePath
    //     }
    // },

    // // 母亲身份证反面图片移除
    // handleAvatarRemove7(response, file) {
    //     this.form.midCardF = ''
    //     this.idcardImg7 = []
    // },
    // // 母亲身份证反面上传成功
    // handleAvatarSuccess7(res, file) {
    //     if (res.code == 200) {
    //         this.form.midCardF = res.data.filePath
    //     }
    // },
    // 身份证图片相关---end----
    // 详情图片上传成功
    handleUploadSuccess(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages = fileList.filter((t) => {
          return t.url.indexOf("blob:") > -1;
        });
      }
    },
    // 详情图片删除
    handleRemove(response, fileList, file) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList.forEach(function (element, key) {
        if (element.url === filePath) {
          that.imgFileList.splice(key, 1); //回显的图片
        }
      });
      this.newImages.forEach(function (element, key) {
        if (element.url === filePath) {
          that.newImages.splice(key, 1); //新上传的图片
        }
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传5张图片");
    },
    close() {
      this.reset();
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="css">
.center {
  text-align: center;
  position: absolute;
  width: 100%;
  bottom: 0;
  left: 0;
  height: 60px;
  background: #fff;
  padding-top: 15px;
}

.form-box {
  max-height: calc(100vh - 20vh - 100px);
  overflow-y: auto;
  overflow-x: hidden;
  padding-top: 20px;
}
.img-box {
  width: 500px;
}
.img-box {
  flex-wrap: wrap;
}
.lin-item {
  width: 100px;
  height: 100px;
  cursor: pointer;
  margin-right: 10px;
  margin-bottom: 10px;
}

.form-box >>> img {
  width: 100%;
}

.form-box >>> .el-upload-dragger {
  width: 148px;
  height: 148px;
}

>>> .el-dialog__body {
  padding: 10px;
}

.form-box >>> .el-form-item__content {
  max-width: 655px;
}

::v-deep .el-input-number.is-without-controls .el-input__inner {
  text-align: left;
}

.hiddenupload >>> .el-upload--picture-card {
  display: none;
}

.checkSmTool {
  width: 900px;
  margin: 0 auto;
  border-radius: 5px;
  border: 1px solid #f1f1f1;
  padding-top: 10px;
  margin-bottom: 15px;
  background-color: #f7f7f7;
}
</style>
